package com.hmdp.utils;

/**
 * @Author wyh
 * @Date 2025/3/17 20:32
 * @description: 全局唯一ID生成器
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
public class RedisIdWorker {
    // 起始时间戳，2025, 1, 1, 0, 0
    private static final long BEGIN_TIMESTAMP = 1735689600L;
    // 序列号位数
    private static final int COUNT_BITS = 32;
    private StringRedisTemplate stringRedisTemplate;
    // 只有一个构造器，会实现自动注入
    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix) {
        // 1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        // 2.生成序列号，用日期作为后缀 key，方便统计和避免计数器溢出
        // 2.1 获取当天日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 2.2 自增，如果没有，Redis会自动创建，初值为1
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        log.debug("生成序列号{}", count);
        // 3.拼接并返回
        return timestamp << COUNT_BITS | count;
    }


/*    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2025, 1, 1, 0, 0);
        time.toEpochSecond(ZoneOffset.UTC);
        log.debug("定义的时间戳为：{}", time.toEpochSecond(ZoneOffset.UTC));//1735689600
    }*/
}
